<?php
namespace Home\Controller;
use Think\Upload\Driver\Qiniu\QiniuStorage;
use Think\Controller;
use Think\Verify;
/**
 * 首页
 * @author yjh
 *
 */
class IndexController extends BaseController {
    public function index(){
        $act_list = session('act_list');
        $menu_list = getMenuList($act_list);
        $this->assign('menu_list',$menu_list);
        $admin_info = getAdminInfo(session('admin_id'));
       // $msg = $this->msg();
        $img = M('admin')->field('img')->where(array('admin_id'=>session('admin_id')))->find();
        //$allmsg = $this->allmsg();
        $admin_info['pname'] = session('pname');
        $admin_info['role'] = session('role');
        $project = $this->project();
        $arr = array(1=>'一',2=>'二',3=>'三',4=>'四',5=>'五',6=>'六',7=>'日');
        $date['m'] = date('m');
        $date['d'] = date('d');
        $date['w'] = date('w');
        
        $this->assign('arr',$arr);
        $this->assign('project',$project);
        $this->assign('msg',$msg);
        $this->assign('date',$date);
        $this->assign('img',$img);
        $this->assign('admin_info',$admin_info);
        $this->display();
    }
    
    /**
     * 查看站内信
     */
    public function ajaxmes(){
        $uid = session('admin_id');
        $Model = M('message');
        $msg = $Model->where(array('addressee'=>$uid,'status'=>0))->order('send_time desc')->select();
        //$msg2 = $Model->where(array('addressee'=>$uid,'status'=>0,'type'=>1))->order('send_time desc')->select();
        //$msg = array_merge($msg1,$msg2);
        $role = M('admin')->getField('admin_id,name');
        if($msg && $role){
            foreach ($msg as $val){
                if($val['type']==1){
                    $val['name'] = '系统提示';
                    $msg1[] = $val;
                }else{
                    $val['name'] =  $role[$val['sender']];
                    $msg2[] = $val;
                }
            }
        }
        
        //去重
        $res = array();
        $st = array(
            'replyid' => array(),
        );
        foreach($msg2 as $t) {
            $flag = true;
            foreach($st as $k=>$v) {
                if(in_array($t[$k], $v)) $flag = false;
                $st[$k][] = $t[$k];
            }
            if($flag) $res[] = $t;
        }
        if(!empty($msg1)){
            $data = array_merge($msg1,$res);
        }else{
            $data = $res;
        }
        
        $this->assign('msg',$data);
        $this->display();
    }
    
    /**
     * 获取当前的项目和可以切换的项目
     */
    public function project(){
        $uid = session('admin_id');
        $where = array();
        $Modal = M('project');
        $sql = "SELECT product_id FROM setpm WHERE find_in_set($uid, `join`)";
        $join = M('')->query($sql);
        if($join){
            foreach ($join as $key=>$val){
                $pid[] = $val['product_id'];
            }
            $pid = implode(',',$pid);
            $map['id'] = array('in',$pid);
            $where = implode(' AND ', $where);
            $dat = $Modal->field('id,name,total_ren')->where($map)->select();
        }   
        $da = $Modal->field('id,name,total_ren')->where('total_ren='.$uid)->order('add_time asc')->select();
           $c = array_merge($dat,$da);
           foreach ($c as $key =>$val){
               $vv=join(',',$val); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
               $temp[$key]=$vv;
           }
           $temp=array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
           foreach ($temp as $k => $v){
               $data[$k]=explode(',',$v); //再将拆开的数组重新组装
           }
           foreach ($data as $k1 =>$v1){
               $data[$k1]['id'] = $data[$k1][0];
               $data[$k1]['name']= $data[$k1][1];
               $data[$k1]['total_ren'] = $data[$k1][2];
               unset($data[$k1][0]);
               unset($data[$k1][1]);
               unset($data[$k1][2]);
           }
           $pid = session(pid);
           if(!is_numeric($pid)){
             if($da){
                session('pid',$da[0]['id']);
                session('pname',$da[0]['name']);
                }else{
                    session('pid',$dat[0]['id']);
                    session('pname',$dat[0]['name']);
                }
          }
           return  $data;
    }
    
    /**
     * 切换项目
     */
    public function swit(){
        $pid = I('post.pid');
        $name = I('post.name');
        $p = session('pid');
        if($p==$pid){
            exit(json_encode(array('errNo'=>1,'msg'=>'已在当前项目,无需切换')));
        }
        session_start();
        $_SESSION['pid'] = $pid;
        $_SESSION['pname'] = $name;
        $pname = session('pname');
           if($pname){
               exit(json_encode(array('errNo'=>0,'msg'=>$pname)));
           }
    }
    
    /**
     * 图表
     */
    public function dataStatis(){
        $pid = session('pid');
        $uid = session('admin_id');
        $mod = M('task');
        if($pid){
            //项目进度查询
            $project = M('project')->where('id='.$pid)->find();
            if($project){
                $d1=strtotime($project['p_start']);
                $d2=strtotime($project['p_stop']);
                $Days=round(($d2-$d1)/3600/24);
                $day['day'] = intval($Days);//总工期
                $Days1 = round(($d2-time())/3600/24);
                $day1 = intval($Days1);
                if($day1 < 0 && time() > $d2){
                    $day['days'] = '已超时'.$day1;//距离竣工天数
                }else{
                    $day['days'] = $day1;
                }
            }
            //我的任务
            $yjh = $this->mytask($pid,$uid);
            $task = $yjh['task'];
            $hour = $yjh['hour'];
            
            //优化点和工程成本统计
            $op['pid'] = array('eq',$pid);
            $op['optimization'] = array('neq',0);
            $organ = M('organization')->field('optimization,status,time_limit,cost,id')->where($op)->select();
                $design =0;
                $optimization=0;
                $check=0;
                $construction=0;
                $time=0;
                $costt=0;
                foreach ($organ as $k=>$v){
                    if($v['status'] != 2 && $v['status'] != 6){
                        if($v['cost'] != 0){
                            $cost[] = $v['cost'];
                        }
                        if(!empty($v['id']) && $v['cost'] !=0 || $v['time_limit'] !=0){
                            $bid[] = $v['id'].'号报告';
                        }
                        if($v['time_limit'] != 0){
                            $time_limit[] = $v['time_limit'];
                        }
                     
                        if($v['optimization'] == 1){
                            $design++;
                        }
                        if($v['optimization'] == 2){
                            $optimization++;
                        }
                        if($v['optimization'] == 3){
                            $check++;
                        }
                        if($v['optimization'] == 4){
                            $construction++;
                        }
                        if($v['optimization'] == 5){
                            $time++;
                        }
                        if($v['optimization'] == 6){
                            $costt++;
                        }
                    }
                }
                
                if($cost == null && $time_limit == null){
                    $gc = 1;
                    $this->assign('gc',$gc);
                }
                
                $num['cost'] = array_sum($cost);
                $num['time_limit'] = array_sum($time_limit);
                $cost = json_encode($cost);
                $time_limit = json_encode($time_limit);
                $bid = json_encode($bid);
                $ordata['design'] = $design;
                $ordata['optimization'] = $optimization;
                $ordata['check'] = $check;
                $ordata['construction'] = $construction;
                $ordata['time'] = $time;
                $ordata['cost'] = $costt;
                $ordata = json_encode($ordata);
                $organs = json_encode(array($design,$optimization,$check,$construction,$time,$costt));
            //项目进度
             $map['type'] = array('neq',3);
             $map['pid'] = array('eq',$pid);
             $ta = $mod->field('link,assign,tid,status,add_time,t_stop,name,type')->where($map)->order('tid desc')->select(); 
             if($ta){
                 $admin = M('admin')->getField('admin_id,name');
                 $sta =array('2'=>'进行中','3'=>'任务超时','4'=>'已通过','5'=>'驳回','7'=>已上传附件待审核,'8'=>待审批);
                 foreach ($ta as $n=>$b){
                     if($b['type']==1){
                         $name = '普通任务';
                     }else{
                         $name = '里程碑任务';
                     }
                     //$result[$b['oid']][]    =   $b;
                     $data[] = array('name'=>$name,'values'=>array(
                         array(
                             'from'=>$b['add_time'] * 1000,
                             'to'=> strtotime($b['t_stop']) * 1000,
                             'desc' => $admin[$b['assign']].'-'.$b['tid'].'号任务-'.($sta[$b['status']]),
                             'label'=>$b['name'],
                             'customClass' => "ganttRed"
                         )
                     ));
                 }
                 $source = json_encode($data);
             }else{
                 $source = 1;
             }
             
             //对里程牌任务查询
             $wher['pid'] = array('eq',$pid);
             $wher['type'] = array('eq',2);
             $wher['link'] = array('eq','');
             $milestone = $mod->field('name,t_stop,status')->where($wher)->order('t_stop')->select(); 
             if(!empty($milestone)){
                 $d1 = time();
                 foreach ($milestone as $m =>$i){
                     $d2=strtotime($i['t_stop']);
                     $tian=round(($d2-$d1)/3600/24);
                     if($d1 > $d2 && $i['status'] != 4){
                         $milestone[$m]['tian'] = 已超时.$tian;
                     }else{
                         $milestone[$m]['tian'] = $tian;
                     }
                 }
                 $this->assign('milestone',$milestone);
             }
             
             //获取概况和阶段性任务详情
             $detail = M('project')->field('stage,profile')->where('id='.$pid)->find();
             if($detail['stage'] == ''){
                 $detail['stage'] = '未填写阶段详情';
             }
             if($detail['profile'] == ''){
                 $detail['profile'] = '未填写概况详情';
             }
        }else{
            $source = 1;
            $gc = 1;
            $this->assign('gc',$gc);
        }
        
        $this->assign('detail',$detail);
        $this->assign('num',$num);
        $this->assign('bid',$bid);
        $this->assign('cost',$cost);
        $this->assign('time_limit',$time_limit);
        $this->assign('hour',$hour);
        $this->assign('ordata',$ordata);
        $this->assign('source',$source);
        $this->assign('task',$task);
        $this->assign('image',$project['image']);
        $this->assign('project',$project);
        $this->assign('organs',$organs);
        $this->assign('day',$day);
        $this->display();
    }
    
    /**
     * 我的任务图表查询
     */
    public function mytask($pid,$uid){
        $tasks = M('task')->field('tid,status,time_stop,add_time,t_stop')->where(array('pid'=>$pid,'assign'=>$uid))->select();//查询任务表我的任务
        //查询内审人ID
        $w = M('process_data')->field('examine_id')->where(array('pid'=>$pid,'typeid'=>1,'eid'=>2))->find();    
        if($w['examine_id']==''){
            $w['examine_id']= 0;
        } 
        $where['pid'] = array('eq',$pid);
        $where['status'] = array(array('neq',1),array('neq',7),'and');
        $res = M('organization')->field('id,uid,status,time_stop,update_time,design,nail')->where($where)->select();
        
        $personal = 0;//针对个人任务百分比
        $conduct = 0;//进行中
        $complete = 0;//已完成
        $delay = 0;//延误'
        $time = time();
        $hour1[] = 0;//进行中
        $hour2[] = 0;//已完成
        $hour3[] = 0;//延误
        //统计任务表的数据
       foreach ($tasks as $key=>$val){
            //进行中
            if($time < strtotime($val['t_stop'])){
                if($val['status'] == 2 || $val['status']==7 || $val['status']==8){
                    $conduct++;
                    $hour1[] = round(($time - $val['add_time'])/86400);
                }
            }
            //已完成
            if($val['status'] == 4){
                $complete++;
                if($val['time_stop'] !=0){
                    $hour2[] = round(($val['time_stop'] - $val['add_time'])/86400);
                }
            }
            //超时
            if($time > strtotime($val['t_stop']) && $val['status'] != 4 && $val['status'] !=5){
                $delay++;
                $hour3[] = round(($time - strtotime($val['t_stop']))/86400); 
               // $hour3[] = str_replace("-", '', $hou3);
            }
        }
        //统计编制报告表的数据
        foreach ($res as $ke=>$va){
            $dtime = $va['update_time'] + 86400;
            //内审方统计
            if($uid==$w['examine_id']){
                //内审进行中
                if($va['status']==5 && $time < $dtime){
                    $conduct++;$personal++;
                    $hour1[] = round(($time - $va['update_time'])/86400);
                }
                //内审完成
                if($va['status']==6){
                    $complete++;$personal++;
                    $hour2[] = round(($va['time_stop'] - $va['update_time'])/86400);
                }
                
                //内审延误
                if($time > $dtime && $va['status'] == 5){
                    $delay++;$personal++;
                    $hour3[] = round(($time - $dtime)/86400);
                }
            }
            
            //甲方统计
            if($uid==$va['nail']){
                //甲方进行中
                if($va['status']==3 && $time < $dtime){
                    $conduct++;$personal++;
                    $hour1[] = round(($time - $va['update_time'])/86400);
                }
                //甲方完成
                if($va['status']==2 || $va['status']==4){
                    $complete++;$personal++;
                    $hour2[] = round(($va['time_stop'] - $va['update_time'])/86400);
                }
                //甲方延误
                if($time > $dtime && $va['status'] == 3){
                    $delay++;$personal++;
                    $hour3[] = round(($time - $dtime)/86400);
                }
            }
            //发起方统计
            if($va['uid']==$uid){
                if($va['status']==2 || $va['status']==6){
                    $conduct++;$personal++;
                    $hour1[] = round(($time - $va['update_time'])/86400);
                }
            }
        }
        
        $task_count = $personal + count($tasks);
        
        //进行中
        if($conduct !=0){
            $hour['hour1'] = array_sum($hour1);
            $hour['bai1'] = round(($conduct/$task_count)*100);
        }else{
            $hour['hour1'] = 0;
            $hour['bai1'] = 0;
        }
        //已完成
        if($complete !=0){
            $hour['hour2'] = array_sum($hour2);
            $hour['bai2'] = round(($complete/$task_count)*100);
        }else{
            $hour['hour2'] = 0;
            $hour['bai2'] = 0;
        }
        //超时
        if($delay !=0){
            $hour['hour3'] = array_sum($hour3);
            $hour['bai3'] = round(($delay/$task_count)*100);
        }else{
            $hour['hour3'] = 0;
            $hour['bai3'] = 0;
        }
        $task = array(
            array('value'=>$complete,'name'=>'已完成'),
            array('value'=>$conduct,'name'=>'进行中'),
            array('value'=>$delay,'name'=>'延误'),
        );
        $task = json_encode($task);
        $data['task'] = $task;
        $data['hour'] = $hour;
        return $data;
    }
    
    /**
     * 图片获取
     */
    public function himg()
    {
        $file_name = I('get.filename'); 
        $setting = C('UPLOAD_FILE_QINIU');
        $Qiniu = new QiniuStorage($setting['driverConfig']);
        $url = $Qiniu->downLink($file_name);
        $file = $Qiniu->privateDownloadUrl($url);
        readfile($file);
       /*  header("Content-type: image/png");
        $url = $file;//图片链接
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_COOKIE,'PHPSESSID=121b1127dcded8702c6a1e702c40eca4');//如果不需要cookies就删除这条语句
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT,0);//忽略超时
        curl_setopt($ch, CURLOPT_NOBODY, false);
        $str = curl_exec($ch);
        curl_close($ch); */
    }
}